<template>
	<div class="layout">
		<div class="market" @click="handleShowMarket">
			<u-icon size="40" name="map"></u-icon>
			<span>{{ nowMarket }}</span>
		</div>
		<div class="search" @click="handleSearch">
			<u-icon name="search"></u-icon>
			{{ res.list[0].title }}
		</div>
		<div slot="right" open-type="contact" class="navbar-right message" @click="linkMsgDetail">
			<image style="width: 53rpx; height: 53rpx; margin-top: 6rpx" src="https://www.haopengsong.xyz/static/img/title.png"></image>
		</div>
		<u-select v-model="show" :list="list" :default-value="defaultMarket" @confirm="confirm"></u-select>
	</div>
</template>
<script>
import { getAllMarket } from "@/api/common.js";
import permision from "@/js_sdk/wa-permission/permission.js";
export default {
	title: "搜索栏",
	props: ["res", "storeId"],
	data() {
		return {
			show: false,
			defaultMarket: [0],
			marketList: [],
			list: [],
			nowMarket: "",
			// 是否已拒绝获取权限
			refuseScope: false
		};
	},
	created() {
		this.getMarkeList();
	},
	methods: {
		/**
		 * 获取市场列表
		 */
		getMarkeList() {
			getAllMarket().then((res) => {
				if (res.data.success) {
					this.marketList = res.data.result;
					if (res.data.result.length > 0) {
						this.list = res.data.result.map((v, index) => {
							return {
								label: v.marketName,
								value: v.id,
								extra: index
							};
						});
						uni.setStorageSync("marketList", JSON.stringify(this.list));
						/*如果已经有默认市场了，不需要再次计算或者给默认了*/
						const market = uni.getStorageSync("nowMarket");
						if (market) {
							this.nowMarket = JSON.parse(market).label;
							return;
						}
						this.setDefaultMarket();
					}
				}
			});
		},
		/**
		 * 设置默认市场
		 * @param showPanel 是否打开市场列表面板
		 */
		setDefaultMarket(showPanel = false) {
			/*如果获取到位置，计算距离*/
			if (uni.getStorageSync("nowGBS")) {
				let copyList = JSON.parse(JSON.stringify(this.marketList));
				copyList.forEach((item, i) => {
					item.i = i;
					item.distanse = this.calcDistance(
						JSON.parse(uni.getStorageSync("nowGBS")).longitude,
						JSON.parse(uni.getStorageSync("nowGBS")).latitude,
						item.marketCenter.split(",")[0],
						item.marketCenter.split(",")[1]
					);
				});
				copyList.sort((a, b) => {
					return a.distanse - b.distanse;
				});
				this.nowMarket = copyList[0].marketName;
				this.defaultMarket = [copyList[0].i];
				uni.setStorageSync(
					"nowMarket",
					JSON.stringify({
						label: copyList[0].marketName,
						value: copyList[0].id
					})
				);
			} else {
				// 没有授权位置，默认第一个
				uni.setStorageSync(
					"nowMarket",
					JSON.stringify({
						label: this.list[0].label,
						value: this.list[0].value
					})
				);
				this.nowMarket = this.list[0].label;
			}

			// 打开市场列表面板
			if (showPanel) {
				this.show = true;
			}
		},
		/**
		 * 跳转到消息列表
		 */
		linkMsgDetail() {
			uni.navigateTo({
				url: `/pages/tabbar/home/title`
			});
		},
		/**
		 * 确认选择市场
		 * @param {Object} e
		 */
		confirm(e) {
			this.defaultMarket = e[0].extra ? [e[0].extra] : [0];
			this.nowMarket = e[0].label;
			uni.setStorageSync("nowMarket", JSON.stringify(e[0]));
			this.$emit("refreshList");
		},
		/**
		 * 搜索
		 */
		handleSearch() {
			if (this.storeId) {
				uni.navigateTo({
					url: `/pages/navigation/search/searchPage?storeId=${this.storeId}`
				});
			} else {
				uni.navigateTo({
					url: `/pages/navigation/search/searchPage`
				});
			}
		},
		/**
		 * 计算2点之间的距离
		 * @param {Object} lat1
		 * @param {Object} lon1
		 * @param {Object} lat2
		 * @param {Object} lon2
		 */
		calcDistance(lat1, lon1, lat2, lon2) {
			const R = 6371e3; // 地球半径
			const φ1 = (lat1 * Math.PI) / 180; // 第一个点的纬度转化为弧度
			const φ2 = (lat2 * Math.PI) / 180; // 第二个点的纬度转化为弧度
			const Δφ = ((lat2 - lat1) * Math.PI) / 180; // 两点纬度之差转化为弧度
			const Δλ = ((lon2 - lon1) * Math.PI) / 180; // 两点经度之差转化为弧度
			const a =
				Math.sin(Δφ / 2) * Math.sin(Δφ / 2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
			const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
			const distance = R * c; // 距离，单位为米
			return distance;
		},
		/**
		 * 打开市场列表
		 */
		handleShowMarket() {
			if (this.refuseScope == true) {
				this.show = true;
			} else {
				this.getAuthorizeInfo();
			}
		},
		/**
		 * 用户授权
		 */
		getAuthorizeInfo() {
			// #ifdef MP-WEIXIN
			uni.authorize({
				scope: "scope.userLocation",
				success: () => {
					// 允许授权
					this.getLocationInfo();
				},
				fail: () => {
					// 拒绝授权
					this.refuseScope = true;
					this.show = true;
					// this.openConfirm();
				}
			});
			// #endif

			// #ifdef APP-PLUS
			if (plus.os.name == "iOS") {
				// ios系统
				if (permision.judgeIosPermission("location")) {
					// 已授权
					this.getLocationInfo();
				} else {
					// 拒绝授权
					this.refuseScope = true;
					this.show = true;
					// this.refuseMap();
				}
			} else {
				// 安卓
				this.requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION");
			}
			// #endif

			// #ifdef H5
			this.getLocationInfo();
			// #endif
		},
		/**
		 * 获取安卓是否拥有地址权限
		 * @param {Object} permisionID
		 */
		async requestAndroidPermission(permisionID) {
			var result = await permision.requestAndroidPermission(permisionID);
			if (result == 1) {
				// 已授权
				this.getLocationInfo();
			} else {
				// 拒绝授权
				this.refuseScope = true;
				this.show = true;
				// this.refuseMap();
			}
		},
		/**
		 * 再次获取授权。当用户第一次拒绝后再次请求授权
		 */
		openConfirm() {
			uni.showModal({
				title: "请求授权当前位置",
				content: "需要获取您的地理位置，请确认授权",
				success: (res) => {
					if (res.confirm) {
						uni.openSetting(); // 打开地图权限设置
					} else if (res.cancel) {
						uni.showToast({
							title: "你拒绝了授权，无法获得当前定位信息",
							icon: "none",
							duration: 1000
						});
					}
				}
			});
		},
		/**
		 * 如果拒绝权限 提示区设置
		 */
		refuseMap() {
			uni.showModal({
				title: "温馨提示",
				content: "您已拒绝定位,请开启",
				confirmText: "去设置",
				success(res) {
					if (res.confirm) {
						//打开授权设置
						// #ifndef MP-WEIXIN
						uni.getSystemInfo({
							success(res) {
								if (res.platform == "ios") {
									//IOS
									plus.runtime.openURL("app-settings://");
								} else if (res.platform == "android") {
									//安卓
									let main = plus.android.runtimeMainActivity();
									let Intent = plus.android.importClass("android.content.Intent");
									let mIntent = new Intent("android.settings.ACTION_SETTINGS");
									main.startActivity(mIntent);
								}
							}
						});
						// #endif
					}
				}
			});
		},
		/**
		 * 获取地理位置
		 */
		getLocationInfo() {
			uni.getLocation({
				type: "wgs84",
				success: (res) => {
					console.log("位置信息：", res);
					// 在这里的得到的经纬度，需要将经纬度转化为中文地理，（山东省青岛市市南区），调用后端的接口做转化
					uni.setStorageSync("nowGBS", JSON.stringify(res));
					this.refuseScope = false;
					this.setDefaultMarket(true);
				},
				fail: (err) => {
					// #ifdef H5
					// 拒绝授权
					this.refuseScope = true;
					this.show = true;
					// #endif
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped>
@import "./tpl.scss";

.search {
	height: 64rpx;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	//justify-content: center;
	background: #ededed;
	padding-left: 20rpx;
	flex: 1;
}
.market {
	max-width: 200rpx;
	display: flex;
	align-items: center;
	width: fit-content;
	margin-right: 20rpx;
	span {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
}

.layout {
	background: #fff;
	padding: 0 16rpx;
	position: relative;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.navbar-right {
	position: relative;
	margin-left: 20rpx;
}
.message {
}
</style>
